package com.wonderful.eyepetizer.data.paging

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.wonderful.eyepetizer.data.entity.bean.Item
import com.wonderful.eyepetizer.data.http.ApiService

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/1/23 16:27
 */
class DailyPagingSource(
    private val apiService: ApiService,
    private val bannerList: MutableList<Item>,
    private var refreshing: MutableState<Boolean>
) : PagingSource<String, Item>() {
    override fun getRefreshKey(state: PagingState<String, Item>): String? = null

    override suspend fun load(params: LoadParams<String>): LoadResult<String, Item> {
        return try {
            Log.d("DailyPagingSource", "key:${params.key} size:${params.loadSize}")
            val pageKey: String? = params.key
            var nextKey: String? = null
            val nextPageUrl: String?
            val daily = if (pageKey.isNullOrEmpty()) {
                refreshing.value = true
                apiService.getDaily()
            } else {
                apiService.getDaily(pageKey)
            }
            nextPageUrl = daily.nextPageUrl
            val itemList = daily.issueList[0].itemList
            itemList.removeAll {
                it.type == "banner2"
            }
            if (pageKey.isNullOrEmpty()) {
                bannerList.clear()
                bannerList.addAll(itemList)
            }
            if (!nextPageUrl.isNullOrEmpty()) {
                nextKey = nextPageUrl
            }
            refreshing.value = false
            LoadResult.Page(if (pageKey.isNullOrEmpty()) emptyList() else itemList, null, nextKey)
        } catch (e: Exception) {
            Log.e("DailyPagingSource", "${e.message}")
            refreshing.value = false
            LoadResult.Error(e)
        }
    }
}